package com.example.menudemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.*
import android.widget.PopupMenu
import android.widget.Toast
import com.example.menudemo.databinding.ActivityMainBinding
import java.lang.Boolean.TYPE
import java.lang.Exception
import java.lang.reflect.Method
import javax.security.auth.callback.Callback

class MainActivity : AppCompatActivity(), PopupMenu.OnMenuItemClickListener {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view:View = binding.root
        setContentView(view)

        registerForContextMenu(binding.etName)

        binding.etName.setOnLongClickListener(View.OnLongClickListener {
            if (actionMode!=null){
                return@OnLongClickListener false
            }
            actionMode = startActionMode(actionModeCallback)
            view.isSelected
            return@OnLongClickListener false
        })
        binding.etPhone.setOnClickListener(View.OnClickListener {
            //创建弹出菜单对象（最低版本11），第二个参数是绑定的那个view
            val popup:PopupMenu = PopupMenu(this,it)
            //获取菜单填充器
            val inflater:MenuInflater = popup.menuInflater
            //填充菜单
            inflater.inflate(R.menu.popup_menu,popup.menu)
            //绑定菜单项的单击事件
            popup.setOnMenuItemClickListener(this)
            //显示弹出菜单
            popup.show()
        })

    }



    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        //加载xml菜单资源
        var inflater:MenuInflater = menuInflater
        inflater.inflate(R.menu.option_menu,menu)
        //动态加载菜单项
        menu?.add(Menu.NONE,Menu.FIRST,3,"帮助")?.setIcon(R.drawable.ic_help)
        //设置菜单添加图标有效
        setIconsVisible(menu,true)

        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        //处理菜单项的选择
        return when(item.itemId){
            R.id.item_download-> {
                Toast.makeText(this,"下载",Toast.LENGTH_LONG).show()
                true
            }
            R.id.item_settings-> {
                Toast.makeText(this,"设置",Toast.LENGTH_LONG).show()
                true
            }
            Menu.FIRST -> {
                Toast.makeText(this,"帮助",Toast.LENGTH_LONG).show()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    //使用反射方法显示图标
    private fun setIconsVisible(menu: Menu?, flag:Boolean){
        //判断menu是否为空
        if(menu != null){
            try {
                val method:Method = menu.javaClass.getDeclaredMethod("setOptionalIconsVisible", TYPE)
                //强制使用方法
                method.isAccessible
                //调用该方法显示icon
                method.invoke(menu,flag)
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }

    override fun onCreateContextMenu(
        menu: ContextMenu?,
        v: View?,
        menuInfo: ContextMenu.ContextMenuInfo?
    ) {
        super.onCreateContextMenu(menu, v, menuInfo)
        if (v?.id == R.id.et_name){
            //加载菜单XML资源
            val inflater:MenuInflater = menuInflater
            inflater.inflate(R.menu.context_menu,menu)
            //动态创建菜单项
//            menu?.add(Menu.NONE,Menu.FIRST,0,"拷贝")
//            menu?.add(Menu.NONE,Menu.FIRST+1,0,"粘贴")
//            menu?.add(Menu.NONE,Menu.FIRST+2,0,"清空")
        }
    }

    override fun onContextItemSelected(item: MenuItem): Boolean {
        return when(item.itemId){
            R.id.item_copy-> {
                Toast.makeText(this,item.title,Toast.LENGTH_LONG).show()
                true
            }
            R.id.item_paste-> {
                Toast.makeText(this,item.title,Toast.LENGTH_LONG).show()
                true
            }
            R.id.item_clear -> {
                binding.etName.setText("")
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    // 上下文操作模式对象
    private var actionMode: ActionMode? = null

    // 实现ActionMode 中 CallBack回调接口
    val actionModeCallback: ActionMode.Callback = object : ActionMode.Callback {
        // 创建方法，在启动上下文操作模式startActionMode(Callback)时调用
        // 在此配置上下文菜单的资源
        override fun onCreateActionMode(mode: ActionMode, menu: Menu?): Boolean {
            mode.menuInflater.inflate(R.menu.context_menu, menu)
            return true
        }

        // 在创建方法后进行调用
        override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
            return false
        }

        // 菜单项被点击，类似onContextItemSelected()方法
        override fun onActionItemClicked(mode: ActionMode?, item: MenuItem): Boolean {
            when (item.itemId) {
                R.id.item_copy -> Toast.makeText(this@MainActivity, "拷贝", Toast.LENGTH_SHORT).show()
                R.id.item_paste -> Toast.makeText(this@MainActivity, "粘贴", Toast.LENGTH_SHORT).show()
                R.id.item_clear -> binding.etName.setText("")
                else -> {
                }
            }
            return true
        }

        // 上下文操作模式结束时被调用
        override fun onDestroyActionMode(mode: ActionMode?) {
            actionMode = null
        }
    }

    // PopupMenu菜单项的点击事件
    override fun onMenuItemClick(item: MenuItem?): Boolean {
        when(item?.itemId){
            R.id.item_copy -> Toast.makeText(this,"复制...",Toast.LENGTH_SHORT).show()
            R.id.item_paste -> Toast.makeText(this,"粘贴...",Toast.LENGTH_SHORT).show()
            else -> {

            }
        }
        return false
    }



}